#include <QDebug>
#include "serialconnection.h"

serialConnection::serialConnection()
{
    serPort = new QSerialPort(this);

    initLink();

    connect(serPort, SIGNAL(error(QSerialPort::SerialPortError)), this,
            SLOT(handleError(QSerialPort::SerialPortError)));
}

serialConnection::~serialConnection()
{
    serPort->close();
}

void serialConnection::initLink()
{

//#ifdef __arm__
//    QString devName = "/dev/ttySAC2";
//#else
//    QString devName = "/dev/ttyUSB0";
//#endif
    QString devName = "\\\\.\\COM5";

    serPort->setPortName(devName);
    serPort->setBaudRate(QSerialPort::Baud9600);
    serPort->setDataBits(QSerialPort::Data8);
    serPort->setParity(QSerialPort::NoParity);
    serPort->setStopBits(QSerialPort::OneStop);
    serPort->setFlowControl(QSerialPort::NoFlowControl);

    if (! serPort->open(QIODevice::ReadWrite)) {

        qDebug()<<devName+",open COM5 failed:"+serPort->errorString();
    }
    else
    {
        qDebug()<<"open COM5 succed！";
    }

    if(!serPort->setBaudRate(QSerialPort::Baud9600))
    {
        qDebug()<<"set baudrate failed："<<serPort->errorString();
    }

    qDebug()<<"baudrate:"<<serPort->baudRate();
}

void serialConnection::handleError(QSerialPort::SerialPortError error)
{
    if(error == QSerialPort::ResourceError)
    {
        qDebug()<<"failed to open serialport:"+serPort->errorString();
    }
}
